﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using MedManager.Model;
using MedManager.Src;
using Maticsoft.DBUtility;

namespace MedManager
{
    public partial class StockInFrm : Form
    {
        public StockInFrm()
        {
            InitializeComponent();
        }

        private List<medInfoEntity> list = Func.medInfoBll.GetModelList("");
        private string pattern = @"^\d{1,7}(\.\d{1,2})?$";

        /// <summary>
        /// 初始化控件
        /// </summary>
        private void InitControl()
        {
            txtDrugID.ReadOnly = true;
            txtDrugName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            txtDrugName.AutoCompleteSource = AutoCompleteSource.CustomSource;
            foreach (medInfoEntity entity in list)
            {
                txtDrugName.AutoCompleteCustomSource.Add(entity.name);
            }
            this.Text = "购药入库！";

        }

        private void ChangeDrugID()
        {
            txtDrugID.Text = "";
            if (!String.IsNullOrEmpty(txtDrugName.Text))
            {
                string sql = "select id from medInfo where name=@name";
                SqlParameter[] sqlParameters = new SqlParameter[1];
                sqlParameters[0] = new SqlParameter("@name", txtDrugName.Text);
                DataSet ds = DbHelperSQL.Query(sql, sqlParameters);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    txtDrugID.Text = ds.Tables[0].Rows[0]["id"].ToString();
                }
            }
        }


        private void SaveStock()
        {
            if (String.IsNullOrEmpty(txtDrugID.Text))
            {
                MessageBox.Show(this, "药品ID不能为空，请重新输入药品名称！");
                txtDrugName.Text = "";
                txtDrugName.Focus();
            }
            else if (String.IsNullOrEmpty(txtShelfLife.Text))
            {
                MessageBox.Show(this, "保质期不能为空！");
                txtShelfLife.Focus();
            }
            else if (String.IsNullOrEmpty(txtPriceIn.Text))
            {
                MessageBox.Show(this, "进价不能为空");
                txtPriceIn.Focus();
            }
            else if (String.IsNullOrEmpty(txtPriceOut.Text))
            {
                MessageBox.Show(this, "售价不能为空！");
                txtPriceOut.Focus();
            }
            else if (String.IsNullOrEmpty(txtAmount.Text))
            {
                MessageBox.Show(this, "进货总量不能为空！");
                txtAmount.Focus();
            }
            else if (String.IsNullOrEmpty(txtTotal.Text))
            {
                MessageBox.Show(this, "总价不能为空！");
                txtTotal.Focus();
            }
            else
            {
                //都合法 保存数据库
                // DbHelperSQL.
                int drugID = Convert.ToInt32(txtDrugID.Text);
                string manu = txtManufacturer.Text;
                DateTime proDate = dtpDate.Value;
                int shelfLife = Convert.ToInt32(txtShelfLife.Text);
                int importer = Src.Func.user.id;
                Decimal priceIn = Convert.ToDecimal(txtPriceIn.Text);
                Decimal priceOut = Convert.ToDecimal(txtPriceOut.Text);
                long amount = Convert.ToInt64(txtAmount.Text);
                Decimal total = Convert.ToDecimal(txtTotal.Text);

                stockinEntity stockIn = new stockinEntity();
                stockIn.medid = drugID;
                stockIn.manufacturers = manu;
                stockIn.productiondate = proDate;
                stockIn.shelflife = shelfLife;
                stockIn.importer = importer;
                stockIn.pricein = priceIn;
                stockIn.priceout = priceOut;
                stockIn.amount = amount;
                stockIn.total = total;
                stockIn.status = 0;
                stockIn.lastamount = amount;

                Src.Func.stockinBll.Add(stockIn);
                string sql = "update medInfo set inventory=inventory+@inventory , price=@price where id=@id";
                SqlParameter[] sqlParameters = new SqlParameter[3];
                sqlParameters[0] = new SqlParameter("@inventory", amount);
                sqlParameters[1] = new SqlParameter("@price", priceOut);
                sqlParameters[2] = new SqlParameter("@id", drugID);
                DbHelperSQL.ExecuteSql(sql, sqlParameters);
                MessageBox.Show("保存成功！");
                Clear();
            }
        }

        private void Clear()
        {
            //TODO
            txtDrugName.Text = "";
            txtDrugID.Text = "";
            txtManufacturer.Text = "";
            txtPriceIn.Text = "";
            txtPriceOut.Text = "";
            txtShelfLife.Text = "";
            dtpDate.Value = DateTime.Now;
            txtAmount.Text = "";
            txtTotal.Text = "";
        }

        /// <summary>
        /// 计算总价
        /// </summary>
        private void CalculateTotal()
        {
            if (!String.IsNullOrEmpty(txtAmount.Text) && !String.IsNullOrEmpty(txtPriceIn.Text))
            {
                //输入框不能为空
                try
                {
                    decimal priceIn = Convert.ToDecimal(txtPriceIn.Text);
                    int amount = Convert.ToInt32(txtAmount.Text);
                    decimal total = priceIn * amount;
                    txtTotal.Text = total.ToString(".00");
                }
                catch (Exception e)
                {
                    //MessageBox.Show(e.Message);
                }
            }else
            {
                txtTotal.Text = "";
            }
        }


        private void StockInFrm_Load(object sender, EventArgs e)
        {
            InitControl();
        }

        private void txtDrugName_Leave(object sender, EventArgs e)
        {
            //TODO

            ChangeDrugID();
        }

        private void txtShelfLife_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = false;
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtAmount_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = false;
            if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8)
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

        private void txtPriceIn_KeyPress(object sender, KeyPressEventArgs e)
        {
            e.Handled = false;
            if (!((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8 || e.KeyChar == 46))
            {
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar == 8)
                {
                    e.Handled = false;
                }
                else if (e.KeyChar == 46)
                {
                    if (txtPriceIn.Text.Length <= 0)
                    {
                        txtPriceIn.Text = "0.";
                        e.Handled = true; //小数点不能在第一位
                        txtPriceIn.SelectionStart = txtPriceIn.Text.Length;
                    }
                    else
                    {
                        Match m1 = Regex.Match(txtPriceIn.Text, @"\.");
                        if (m1.Success)
                        {
                            e.Handled = true;
                        }
                        else
                        {
                            e.Handled = false;
                        }
                    }
                }
                else
                {
                    Match m = Regex.Match(txtPriceIn.Text + e.KeyChar, pattern);
                    if (m.Success)
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }
            }
        }

        private void txtPriceOut_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8 || e.KeyChar == 46))
            {
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar == 8)
                {
                    e.Handled = false;
                }
                else if (e.KeyChar == 46)
                {
                    if (txtPriceOut.Text.Length <= 0)
                    {
                        txtPriceOut.Text = "0.";
                        e.Handled = true; //小数点不能在第一位
                        txtPriceOut.SelectionStart = txtPriceOut.Text.Length;
                    }
                    else
                    {
                        Match m1 = Regex.Match(txtPriceOut.Text, @"\.");
                        if (m1.Success)
                        {
                            e.Handled = true;
                        }
                        else
                        {
                            e.Handled = false;
                        }
                    }
                }
                else
                {
                    Match m = Regex.Match(txtPriceOut.Text + e.KeyChar, pattern);
                    if (m.Success)
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }
            }
        }

        private void txtTotal_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == 8 || e.KeyChar == 46))
            {
                e.Handled = true;
            }
            else
            {
                if (e.KeyChar == 8)
                {
                    e.Handled = false;
                }
                else if (e.KeyChar == 46)
                {
                    if (txtTotal.Text.Length <= 0)
                    {
                        txtTotal.Text = "0.";
                        e.Handled = true; //小数点不能在第一位
                        txtTotal.SelectionStart = txtTotal.Text.Length;
                    }
                    else
                    {
                        Match m1 = Regex.Match(txtTotal.Text, @"\.");
                        if (m1.Success)
                        {
                            e.Handled = true;
                        }
                        else
                        {
                            e.Handled = false;
                        }
                    }
                }
                else
                {
                    Match m = Regex.Match(txtTotal.Text + e.KeyChar, pattern);
                    if (m.Success)
                    {
                        e.Handled = false;
                    }
                    else
                    {
                        e.Handled = true;
                    }
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveStock();
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Clear();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 进货量按键抬起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtAmount_KeyUp(object sender, KeyEventArgs e)
        {
            CalculateTotal();
        }

        /// <summary>
        /// 进货单价按键抬起事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtPriceIn_KeyUp(object sender, KeyEventArgs e)
        {
            CalculateTotal();
        }
    }
}
